<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>药品管理</el-breadcrumb-item>
      <el-breadcrumb-item>药品信息</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 选择器--药品 -->
    <div class="block">
      <el-input placeholder="搜索药品信息（药品名字 / 药品ID)" style="width: 250px" v-model="params.query"></el-input>
      <el-button type="primary" @click="searchMedicine">搜索</el-button>
      <el-button type="primary" @click="reback">撤回</el-button>
    </div>
    <!--------------- 卡片部分 -- 显示信息 --------------->
    <el-card shadow="never" border="false">
      <!----- 卡片头部 ------>
      <template>
        <div class="header">
          <span>共{{ total }}条记录</span>
          <el-button icon="el-icon-plus" size="small" type="primary" style="float: right" @click="addMedicineInfo">添加药品信息</el-button>
        </div>
      </template>
      <!----- 卡片的内容 ----->
      <el-table style="width: 100%" :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }" :data="medicineList">
        <!--- 药品信息 --->
        <el-table-column type="expand" label="详细信息" width="140px">
          <template slot-scope="{ row }">
            <!-- 详细信息部分 -->
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="药品编号：">
                <span>{{ row.medicineID }}</span>
              </el-form-item>
              <el-form-item label="药品名称：">
                <span>{{ row.name }}</span>
              </el-form-item>
              <el-form-item label="药品规格：">
                <span>{{ row.size }}</span>
              </el-form-item>
              <el-form-item label="药品类型：">
                <span>{{ row.type }}</span>
              </el-form-item>
              <el-form-item label="处方药：">
                <span>{{ row.oTC == true ? '是' : '否' }}</span>
              </el-form-item>
              <el-form-item label="供应商编号：">
                <span>{{ row.supplier }}</span>
              </el-form-item>
              <el-form-item label="售价：">
                <span>{{ row.price }}</span>
              </el-form-item>
              <el-form-item label="保质期：">
                <span>{{ row.shelfLife }}</span>
              </el-form-item>
              <el-form-item label="入库时间：">
                <span>{{ row.day }}</span>
              </el-form-item>
              <el-form-item label="所处货架：">
                <span>{{ row.shelf }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="药品编号" prop="medicineID" sortable> </el-table-column>
        <el-table-column label="药品名称" prop="name"> </el-table-column>
        <el-table-column label="库存" prop="count"> </el-table-column>
        <el-table-column prop="status" label="库存状态" width="100">
          <template slot-scope="scope">
            <el-tag v-show="ldShowStatus(scope.row)" :type="scope.row.status === '库存充足' ? 'primary' : scope.row.status === '库存紧张' ? 'warning' : 'danger'" disable-transitions>{{
              scope.row.status
            }}</el-tag>
          </template>
        </el-table-column>
        <!--- 基本操作 --->
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <div class="actions">
              <!-- 修改信息 -->
              <i class="el-icon-edit-outline" @click="editMedicine(row)"></i>
              <!-- 删除信息 -->
              <i class="el-icon-delete" @click="deleteMedicine(row)"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页： handleSizeChange:每页条数变化触发；handleCurrentChange：当前页改变触发；current-page：当前页；page-size：每页显示多少条；layout：排版布局-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pageStart"
        :page-sizes="[5, 10, 15]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加/编辑抽屉： title：标题； :visible.sync 控制打开/关闭；direction：控制打开方向；before-close：关闭之前执行的方法；size：控制大小-->
    <el-drawer :title="flag" :visible.sync="drawer" :direction="direction" :before-close="handleClose" size="48%">
      <!--  抽屉内容部分：添加、修改操作===》表单  -->
      <el-form label-width="auto" :model="addDrug" :rules="rules" ref="addDrug">
        <el-form-item label="药品ID:" prop="medicineID"><el-input v-model="addDrug.medicineID" placeholder="格式：YCP-XXXX"></el-input></el-form-item>
        <el-form-item label="药品名称:" prop="name"><el-input v-model="addDrug.name"></el-input></el-form-item>
        <!-- gutter:栅格间隔; span:栅格占据的列数-->
        <el-row :gutter="0">
          <el-col :span="8"
            ><el-form-item label="规格:" prop="size"><el-input v-model="addDrug.size"></el-input></el-form-item
          ></el-col>
          <el-col :span="8"
            ><el-form-item label="类型:" prop="type"><el-input v-model="addDrug.type"></el-input></el-form-item
          ></el-col>
          <el-col :span="8" :offset="1" style="margin-left: 0"
            ><el-form-item label="处方药:" prop="oTC">
              <el-radio v-model="addDrug.oTC" label="Y" style="margin-right: 10px">是</el-radio>
              <el-radio v-model="addDrug.oTC" label="N">否</el-radio>
            </el-form-item></el-col
          >
          <el-col :span="13"
            ><el-form-item label="供应商ID:" placeholder="格式：SYXXX" prop="supplier"><el-input v-model="addDrug.supplier"></el-input></el-form-item
          ></el-col>
          <el-col :span="8" :offset="3"
            ><el-form-item label="售价:" prop="price"><el-input v-model.number="addDrug.price"></el-input></el-form-item
          ></el-col>
          <el-col :span="13">
            <el-form-item label="入库时间:" prop="day">
              <template>
                <el-date-picker v-model="addDrug.day" type="date" placeholder="格式：XXXX-X-X" style="width: 200px"> </el-date-picker>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="3">
            <el-form-item label="保质期:" prop="shelfLife"><el-input v-model="addDrug.shelfLife"></el-input></el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item label="货架ID:" prop="shelf"><el-input v-model="addDrug.shelf" placeholder="格式：G-XX-XXX"></el-input></el-form-item>
          </el-col>
          <el-col :span="8" :offset="3">
            <el-form-item label="库存:" prop="count"><el-input v-model.number="addDrug.count"></el-input></el-form-item>
          </el-col>
        </el-row>
        <br /><br />
        <!-- 操作部分：添加/取消 -->
        <el-form-item>
          <el-col :span="8" :offset="5">
            <el-button type="primary" @click="onSubmit()">{{ flag == '添加药品信息' ? '立即添加' : '立即修改' }}</el-button>
          </el-col>
          <el-button @click="handleClose">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { mapState } from 'vuex';
export default {
  name: 'Medicine',
  data() {
    return {
      params: {
        query: '',
        pageStart: 1,
        pageSize: 5,
      },
      drawer: false, //false-关闭抽屉，true-打开抽屉
      direction: 'rtl', //打开方式：从右往左
      //添加药品的对象属性
      addDrug: {
        medicineID: '',
        name: '',
        size: '',
        type: '',
        OTC: '',
        supplier: '',
        price: undefined,
        shelfLife: '',
        day: '',
        shelf: '',
        count: '',
        status: '',
      },
      //表单验证
      rules: {
        medicineID: [
          { required: true, message: '药品ID不能为空', trigger: 'blur' },
          { pattern: /^YCP-\d{4}$/, message: '格式：YCP-XXXX', trigger: 'blur' },
        ],
        name: [{ required: true, message: '药品名称不能为空', trigger: 'blur' }],
        size: [{ required: true, message: '规格不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '类型不能为空', trigger: 'blur' }],
        shelfLife: [{ required: true, message: '保质期不能为空', trigger: 'blur' }],
        day: [{ required: true, message: '入库时间不能为空', trigger: 'blur' }],
        shelf: [{ required: true, message: '货架编号不能为空', trigger: 'blur' }],
        price: [{ type: 'number', message: '价格只能为整型', trigger: 'blur' }],
        count: [{ type: 'number', message: '库存只能为整型', trigger: 'blur' }],
      },
      flag: '', //控制表单头部
    };
  },
  mounted() {
    //发请求获取所有药品信息
    this.$store.dispatch('getMedicineList', this.params);
  },
  computed: {
    //从store获取数据
    ...mapState({ medicineList: state => state.medicine.medicineList || [], total: state => state.medicine.total || 0 }),
  },
  methods: {
    // 监听pageSize改变的事件
    handleSizeChange(newSize) {
      this.params.pageSize = newSize;
      this.$store.dispatch('getMedicineList', this.params); // 数据发生改变重新申请数据
    },
    // 监听pageStart改变的事件
    handleCurrentChange(newPage) {
      this.params.pageStart = newPage;
      this.$store.dispatch('getMedicineList', this.params); // 数据发生改变重新申请数据
    },
    //搜索按钮的回调
    searchMedicine() {
      //发请求获取搜索结果
      this.params.pageStart = 1;
      this.$store.dispatch('getMedicineList', this.params);
    },
    //撤回按钮的回调
    reback() {
      //清空搜索框里的数据
      this.params.query = '';
      this.$store.dispatch('getMedicineList', this.params).then(res => {
        //重新获取数据
        Object.assign(this.medicineList, this.$store.state.medicine.medicineList);
      });
    },
    //添加药品信息
    addMedicineInfo() {
      this.drawer = true;
      this.flag = '添加药品信息';
    },
    // 关闭抽屉的回调
    handleClose() {
      this.drawer = false;
      //清空表单
      Object.assign(this._data.addDrug, this.$options.data().addDrug);
      //清除表单验证提示
      this.$nextTick(() => {
        this.$refs.addDrug.clearValidate();
      });
    },
    //提交表单
    onSubmit() {
      //添加药品
      //将时间对象转为以-连接的字符串
      const day = new Date(this.addDrug.day);
      const formattedTime = day.toLocaleString('zh-CN', { hour12: false });
      this.addDrug.day = formattedTime.split('/').join('-');
      this.$refs.addDrug.validate(valid => {
        //如何符合表单填写要求，则发送请求
        if (valid) {
          //发送请求，添加药品数据
          this.$store
            .dispatch('addMedicine', this.addDrug)
            .then(res => {
              //提示添加成功
              this.$message({
                message: '添加药品成功',
                type: 'success',
              });
              //关闭添加药品对话框
              this.drawer = false;
              //清空表单
              Object.assign(this._data.addDrug, this.$options.data().addDrug);
              //发送请求，重新获取本页面的数据
              this.$store.dispatch('getMedicineList', this.params);
            })
            .then(res => {
              //重新获取数据
              Object.assign(this.medicineList, this.$store.state.medicine.medicineList);
            });
        } else {
          this.$message({
            message: '添加失败,请确认药品信息是否正确',
            type: 'error',
          });
        }
      });
    },
    //编辑药品信息
    editMedicine(row) {
      this.drawer = true;
      //浅拷贝
      this.addDrug = Object.assign({}, row);
      this.flag = '修改药品信息';
    },
    //删除药品信息
    deleteMedicine(row) {
      this.$confirm('此操作将永久删除该药品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(
          //删除药品信息
          this.$store.dispatch('deleteMedicine', row.id)
        )
        .then(res => {
          if (this.medicineList.length == 1) {
            //如果当前页没有数据了，就往前跳一页
            this.params.pageStart = this.params.pageStart - 1;
          }
          //重新获取药品信息
          this.$store.dispatch('getMedicineList', this.params);
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    //tag标签设置
    ldShowStatus(row) {
      if (row.status == '') {
        if (row.count == 0) row.status = '无库存';
        else if (row.count <= 50) row.status = '库存紧张';
        else row.status = '库存充足';
      }
      return 1;
    },
  },
};
</script>

<style lang="less" scoped>
//Breadcrumb 面包屑样式
.el-breadcrumb {
  margin-top: 10px;
  margin-bottom: 25px;
}
.block {
  .el-button {
    margin-left: 10px;
  }
}
//卡片部分样式
.el-card {
  margin-top: 25px;
  //卡片头部样式
  .header {
    align-items: center;
    padding-right: 16px;
  }
  .el-table {
    //表格样式
    .demo-table-expand {
      padding: 0 40px;
      margin: 0 50px;
      font-size: 0;
    }
    .demo-table-expand label {
      width: 90px;
      color: #99a9bf;
    }
    .demo-table-expand .el-form-item {
      margin-right: 0;
      margin-bottom: 0;
      width: 50%; //每行显示数量
    }

    //插槽内图标样式
    .actions {
      font-size: 18px; //图标大小
      display: flex;
      justify-content: space-around;
      color: #666;
      //交互效果
      > i:hover {
        color: rgba(114, 124, 245, 1); //鼠标滑动时，图标颜色改变
        cursor: pointer; //鼠标移动显示小手
      }
    }
  }

  //分页样式
  .el-pagination {
    margin-top: 20px; //上边距
    text-align: center; //字体居中
  }
}
//抽屉部分样式
.el-drawer {
  .el-form {
    padding: 0 30px;
  }
}
</style>